/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dbcontrollers;

import dbbeans.Fields;
import dbcontrollers.exceptions.NonexistentEntityException;
import dbcontrollers.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;

/**
 *
 * @author Laur
 */
public class FieldsJpaController implements Serializable {

    /**
     * constructor used to instantiate this controller using a transaction and an emf
     * @param utx
     * @param emf 
     */
    public FieldsJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    // method used to add a new row in the DB table
    public void create(Fields fields) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin(); // begin of the transaction
            em = getEntityManager(); // call for em
            em.persist(fields); // call of persist to add the new row
            utx.commit(); // commit of the transaction
        } catch (Exception ex) {
            try {
                utx.rollback(); // rollback the transaction in case of exception
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    /**
     * Method used to  update a row in the table
     * @param fields
     * @throws NonexistentEntityException
     * @throws RollbackFailureException
     * @throws Exception 
     */
    public void edit(Fields fields) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin(); // begin of transaction
            em = getEntityManager(); // call for entity manager
            fields = em.merge(fields); // update using the new information from the bean instance sent by parameter
            utx.commit(); // commit the transaction
        } catch (Exception ex) {
            try {
                utx.rollback(); // in case of an exception rollback the transaction
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = fields.getId();
                if (findFields(id) == null) {
                    throw new NonexistentEntityException("The fields with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Fields fields;
            try {
                fields = em.getReference(Fields.class, id);
                fields.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The fields with id " + id + " no longer exists.", enfe);
            }
            em.remove(fields);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Fields> findFieldsEntities() {
        return findFieldsEntities(true, -1, -1);
    }

    public List<Fields> findFieldsEntities(int maxResults, int firstResult) {
        return findFieldsEntities(false, maxResults, firstResult);
    }

    private List<Fields> findFieldsEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Fields.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Fields findFields(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Fields.class, id);
        } finally {
            em.close();
        }
    }

    public int getFieldsCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Fields> rt = cq.from(Fields.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
